package org.liquidByte.trafficMustang.androidApp.activities;

import org.liquidByte.trafficMustang.R;
import org.liquidByte.trafficMustang.androidApp.App;
import org.liquidByte.trafficMustang.androidApp.services.DeslocamentoService;
import org.liquidByte.trafficMustang.androidApp.services.RastreamentoService;
import org.liquidByte.trafficMustang.androidApp.services.Services;
import org.liquidByte.trafficMustang.androidApp.services.VeiculoService;
import org.liquidByte.trafficMustang.androidApp.services.dto.DeslocamentoDTO;
import org.liquidByte.trafficMustang.androidApp.services.dto.LocalizacaoDTO;
import org.liquidByte.trafficMustang.androidApp.services.dto.VeiculoDTO;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;

public class InformarDeslocamentoActivity extends AbstractActivity implements OnClickListener {

	private static final int REQUEST_CODE_SELECIONAR_LOCALIZACAO = 1;
	
	private Spinner spnVeiculo;
	private EditText edtxTaxa;
	private ImageButton imgbLocalizacao;
	private ImageButton imgbConfirmar;
	private ImageButton imgbCancelar;
	private LocalizacaoDTO localizacao;
	private ArrayAdapter<VeiculoWrapper> adapter;
	
	protected Spinner getSpnVeiculo() {
		if (this.spnVeiculo == null) {
			this.spnVeiculo = (Spinner)this.findViewById(R.id.activity_informar_deslocamento_spnVeiculo);
		}
		return spnVeiculo;
	}
	protected EditText getEdtxTaxa() {
		if (this.edtxTaxa == null) {
			this.edtxTaxa = (EditText)this.findViewById(R.id.activity_informar_deslocamento_edtxTaxa);
		}
		return edtxTaxa;
	}
	protected ImageButton getImgbLocalizacao() {
		if (this.imgbLocalizacao == null) {
			this.imgbLocalizacao = (ImageButton)this.findViewById(R.id.activity_informar_deslocamento_imgbLocalizacao);
		}
		return imgbLocalizacao;
	}
	protected ImageButton getImgbConfirmar() {
		if (this.imgbConfirmar == null) {
			this.imgbConfirmar = (ImageButton)this.findViewById(R.id.activity_informar_deslocamento_imgbConfirmar);
		}
		return imgbConfirmar;
	}
	protected ImageButton getImgbCancelar() {
		if (this.imgbCancelar == null) {
			this.imgbCancelar = (ImageButton)this.findViewById(R.id.activity_informar_deslocamento_imgbCancelar);
		}
		return imgbCancelar;
	}
	protected ArrayAdapter<VeiculoWrapper> getAdapter() {
		if (this.adapter == null) {
			this.adapter = new ArrayAdapter<InformarDeslocamentoActivity.VeiculoWrapper>(this, android.R.layout.simple_spinner_item);
			this.adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		}
		return adapter;
	}
	private void cancel() {
		this.setResult(Activity.RESULT_CANCELED);
		this.finish();
	}
	private void confirm() {
		this.setResult(Activity.RESULT_OK);
		this.finish();
	}
	private void loadData() {
		this.getAdapter().clear();
		VeiculoService service = Services.veiculo();
		try {
			for (VeiculoDTO item : service.get()) {
				this.getAdapter().add(new VeiculoWrapper(item));
			}
		} catch (Exception e) {
			App.error(e);
		}
	}
	private void selecionarLocalizacao() {
		Intent intent = new Intent(this, VisualizarLocalizacaoActivity.class);
		this.startActivityForResult(intent, REQUEST_CODE_SELECIONAR_LOCALIZACAO);
	}
	private String formatValidateError(int taxaResource, int errorResource) {
		return String.format("%s: %s", this.getResources().getString(taxaResource), this.getResources().getString(errorResource));
	}
	private boolean validate() {
		StringBuilder sb = new StringBuilder();
		boolean valid = true; 
		if (this.getEdtxTaxa().getText().toString().equals("")) {
			sb.append(this.formatValidateError(R.string.msgs_taxa, R.string.msgs_campo_requerido));
			valid = false;
		}
		if (this.getSpnVeiculo().getSelectedItem() == null) {
			if (sb.length() > 0) {
				sb.append("\r\n");
			}
			sb.append(this.formatValidateError(R.string.msgs_veiculo, R.string.msgs_campo_requerido));
			valid = false;
		}
		if (this.localizacao == null) {
			if (sb.length() > 0) {
				sb.append("\r\n");
			}
			sb.append(this.formatValidateError(R.string.msgs_localizacao, R.string.msgs_campo_requerido));
			valid = false;
		}
		if (!valid) {
			App.validationError(sb.toString());
		}
		return valid;
		
	}
	private boolean informarDeslocamento() {
		if (this.validate()) {
			DeslocamentoDTO deslocamento = new DeslocamentoDTO();
			try {
				deslocamento.setTaxa(Double.parseDouble(this.getEdtxTaxa().getText().toString()));
			} catch (NumberFormatException e) {
				App.error(e);
				return false;
			}
			
			deslocamento.setVeiculo(((VeiculoWrapper)this.getSpnVeiculo().getSelectedItem()).getWrappedData());
			deslocamento.setLocalizacao(this.localizacao);
			
			DeslocamentoService service = Services.deslocamento();
			RastreamentoService rastrService = Services.rastreamento();
			try {
				service.informar(deslocamento);
				rastrService.update();
				return true;
			} catch (Exception e) {
				App.error(e);
				return false;
			}
		} else {
			return false;
		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == REQUEST_CODE_SELECIONAR_LOCALIZACAO && resultCode == Activity.RESULT_OK) {
			this.localizacao = (LocalizacaoDTO)data.getSerializableExtra(LocalizacaoDTO.class.getName());
		}
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_informar_deslocamento);
		
		this.getImgbCancelar().setOnClickListener(this);
		this.getImgbConfirmar().setOnClickListener(this);
		this.getImgbLocalizacao().setOnClickListener(this);
		
		this.getSpnVeiculo().setAdapter(this.getAdapter());
		this.loadData();
	}
	@Override
	public void onClick(View v) {
		if (this.getImgbCancelar() == v) {
			this.cancel();
		} else if (this.getImgbConfirmar() == v) {
			if (this.informarDeslocamento()) {
				this.confirm();
			}
		} else if (this.getImgbLocalizacao() == v) {
			this.selecionarLocalizacao();
		}
	}
	
	private class VeiculoWrapper {
		private VeiculoDTO veiculo;

		protected VeiculoWrapper(VeiculoDTO veiculo) {
			this.veiculo = veiculo;
		}
		
		protected VeiculoDTO getWrappedData() {
			return veiculo;
		}
		
		@Override
		public String toString() {
			return this.veiculo.getModelo() + "(" + this.veiculo.getPlaca() + ")";
		}
	}
}
